<template>
  <div ref="chartRef" class="trend-chart"></div>
</template>

<script setup lang="ts">
import {ref, onMounted, onBeforeUnmount, watch, computed} from 'vue'
import * as echarts from 'echarts'
import type {ChartsTrend} from "@/api/statistics/type.ts";

interface Props {
  data: ChartsTrend[]
  type: 'line' | 'bar'
}

const props = defineProps<Props>()


const chartRef = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null

const renderChart = () => {
  if (!chartRef.value) return

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['收入', '支出']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: props.data.map((item: any) => item.time)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '收入',
        type: props.type,
        data: props.data.map((item: any) => item.income),
        itemStyle: {
          color: '#67C23A'
        },
        smooth: true
      },
      {
        name: '支出',
        type: props.type,
        data: props.data.map((item: any) => item.expense),
        itemStyle: {
          color: '#F56C6C'
        },
        smooth: true
      }
    ]
  }

  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }

  chartInstance.setOption(option)
}

onMounted(() => {
  renderChart()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
})

const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

watch(() => props.type, renderChart)
watch(() => props.data, renderChart, { deep: true })
</script>

<style scoped lang="scss">
.trend-chart {
  width: 100%;
  height: 100%;
}
</style>
